//
//  AuctionListVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/15.
//

import UIKit
import JXPagingView

class AuctionListVC: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {

    //MARK: --------------------属性--------------------
    var scrollViewDidScrollBlock: ((UIScrollView) -> ())?

    var activity : AuctionModels.Acitivity!
    
    var listData = [AuctionModels.Goods]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    
    let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    let changeString = ZMUtil.fastBehavior(value: ChangeTitle())
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
    }
    
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        bindAction()
        addConstraints()
        getList()
    }

    //MARK: --------------------UI--------------------
    func setUI() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 141
        tableView.rowHeight = UITableView.automaticDimension
        view.addSubview(tableView)
        tableView.zm.register(nibName: "AuctionCell", reuserId: "AuctionCell")
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.getList()
        }
        
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        timer.subscribe(onNext:{ [unowned self] resp in
            self.changeString.accept(self.getTipsString())
        }).disposed(by: disposeBag)
        
        
    }
    
    // 更新当前文字显示
    func getTipsString() -> ChangeTitle {
        let change = ChangeTitle()
        guard let ac = activity else {return change}
        let start = AuctionService.shared.dateFromToday(.milliseconds(ac.startTime))
        let end = AuctionService.shared.dateFromToday(.milliseconds(ac.endTime))
        if ac.state == .wait {
            change.wait = "\(start.zm.toString("HH:mm"))-\(end.zm.toString("HH:mm"))"
        } else if ac.state == .process {
            let endTimeInterval = end.timeIntervalSince1970
            let count = AppHelper.countTime(now: RedBagService.shared.nowTimeinterval, end: endTimeInterval)
            change.h = String(format: "%02d", count.h)
            change.m = String(format: "%02d", count.m)
            change.s = String(format: "%02d", count.s)
        }
        return change
    }
    
    func refresh() {
        page = 1
        getList()
    }
    
    func getList() {
        let pa = ["activityId" : activity.id, "page" : page, "size" : pageSize] as [String : Any]
        let begin = Date()
        ZMAPIManage<[AuctionModels.Goods]>.rxSendRequest(AuctionAPI.getAuctionList(pa)).subscribe(onNext:{ [unowned self] resp in
            listRequest(resp)
            XMLogger.info("列表请求耗时：\(Date().timeIntervalSince1970 - begin.timeIntervalSince1970)S")
        }).disposed(by: disposeBag)
    }
    
    // 点击竞拍按钮
    func onJpBtn(goods : AuctionModels.Goods) {
//        NotificationTool.shard.addNotifaction(identifier : "第\(indexPath.row)个", timeInterval: 10)
        if goods.bidState == .wait {
            // 提醒
            let idStr = AuctionService.shared.generateNotificationIdstr(goods.id, activity.id)

            if NotificationTool.shard.checkNotificationExist(idStr) {
                // 存在->取消提醒
                NotificationTool.shard.cancelNotification(idStr)
            } else {
                // 不存在->提醒
                var startDate = AuctionService.shared.dateFromToday(.milliseconds(activity.startTime))
                let adDate = startDate - (60 * 3)
                let diff = adDate.timeIntervalSince1970 - RedBagService.shared.nowTimeinterval
                if diff <= 0 {
                    ZMToast.showToast(title: "距离开始时间不足3分钟")
                    return
                }
                NotificationTool.shard.addNotifaction(identifier: idStr, timeInterval: diff, title: "乐购竞购提醒", subtitle: "有一场竞购即将开始", body: "有一场 \(startDate.zm.toString("HH:mm")) 的竞购活动即将开始")
                ZMToast.showToast(title: "预约成功，将在开抢前3分钟提醒")
            }
            NotificationTool.shard.getNotification({ [weak self] in
                guard let self = self else {return}
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            })
        } else if goods.bidState == .process {
            // 竞拍
            let vc = AuctionDetailVC()
            vc.id = goods.id
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            
        }
    }
    

    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = listData[indexPath.row]
        let vc = AuctionDetailVC()
        vc.id = data.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AuctionCell") as! AuctionCell
        let data = listData[indexPath.row]
        
        cell.avatar.zm.setImage(urlStr: data.image)
        cell.dateNum.text = "第\(data.currentRound)期"
        cell.name.text = data.name
        cell.moneyBtn.setTitle("赚¥\(data.maxReward.zm.xmToString(keep: 2))", for: .normal)
        cell.currentMoney.text = data.getcurrentMoney.zm.toString(keep: 2)
        cell.currentMoney.textColor = Style.mainColor
        cell.setStyle(type: data.bidState)
        cell.markPrice.zm.setStrikethroughTitle(title: "市场价 ￥\(data.marketPrice.zm.roundingDown(keep: 2))")
        if data.bidState == .wait {
            cell.otherJion.text = "围观\(data.viewer)次"
            if NotificationTool.shard.checkNotificationExist(AuctionService.shared.generateNotificationIdstr(data.id, activity.id)) {
                cell.setJionButtonStyle(type: 2)
            } else {
                cell.setJionButtonStyle(type: 1)
            }
            cell.dqj.text = "起购价¥"
            cell.currentMoney.text = data.startPrice.zm.toString(keep: 2)
        } else if data.bidState == .process {
            cell.otherJion.text = "围观\(data.viewer)次 已出价\(data.bidCount)人"
            cell.jion.setTitle("参与 \(data.joinTime) 次", for: .normal)
            cell.dqj.text = "当前价¥"
            cell.currentMoney.textColor = Style.mainColor
            cell.setJionButtonStyle(type: 0)
            cell.currentMoney.text = data.getcurrentMoney.zm.toString(keep: 2)
        } else {
            cell.otherJion.text = "围观\(data.viewer)次 已出价\(data.bidCount)人"
            cell.jion.setTitle("参与 \(data.joinTime) 次", for: .normal)
            cell.dqj.text = "竞购价¥"
        }
        
        changeString.subscribe(onNext:{ [unowned self] resp in
            if let w = resp.wait {
                cell.alerView.timeLabel.text = w
            } else {
                cell.auctionBtn.s.setTitle(resp.s, for: .normal)
                cell.auctionBtn.h.setTitle(resp.h, for: .normal)
                cell.auctionBtn.m.setTitle(resp.m, for: .normal)
            }
        }).disposed(by: cell.disposeBag)
            
        cell.alerView.onClick = { [unowned self] in
            self.onJpBtn(goods: data)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let c = cell as? AuctionCell else {return}
    }
    
    func scrollViewDidScroll(_ scrollViewDidScorllBolck: @escaping ((UIScrollView) -> ())) {
        scrollViewDidScrollBlock = scrollViewDidScorllBolck
    }
}

extension AuctionListVC : JXPagingViewListViewDelegate {
    func listScrollView() -> UIScrollView { tableView }
    
    func listView() -> UIView {
        return view
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let scrollViewDidScrollBlock = scrollViewDidScrollBlock {
            scrollViewDidScrollBlock(scrollView)
        }
        listViewDidScrollCallback?(scrollView)
    }
}

extension AuctionListVC {
    class ChangeTitle {
        var wait : String? = nil
        var h = "0"
        var m = "0"
        var s = "0"
    }
}
